// 该组件事路由守卫组件
import { useRoutes, useLocation, useNavigate } from 'react-router-dom'
import { useEffect } from 'react'
import { message } from 'antd'
import router from '@/router'
import useStore from '@/store/index'


function BeforeRouterEnter() {
    const outLet = useRoutes(router)
    const storeGetUser =  useStore((state:any)=>state.getUser)
    let location = useLocation()
    let NavigateTo = useNavigate()
    let token = localStorage.getItem('token')
    if(token){
        storeGetUser().then((storeGetUserRes:any)=>{
            if(storeGetUserRes ==200){
                // console.log('令牌没有过期');
            }else{
                NavigateTo('/login')
                message.warning(storeGetUserRes);
            }
        })
    }
    useEffect(() => {
        
        // 1.如果没有token不在登录页，就跳转到登录页
        if (!token && location.pathname !== '/login') {
            // 没有token
            // return <ToLogin />
            // window.location.pathname = '/login'
            NavigateTo('/login')
            message.warning('未登录,请先登录');
            // 2.如果有token并且没过期不在登录页，就跳转到首页
        } 
        else if (token && location.pathname == '/login'  ) {   
            // return <ToHome />
            // window.location.pathname = '/'
            NavigateTo('/')
            message.warning('已登录,请先退出登录');
    }
    }, [])
    
    
    return outLet
    
}
export default BeforeRouterEnter